<template>
  <div class="activity-add">
    <el-page-header @back="goBack" :title="isView ? '查看活动' : (isEdit ? '编辑活动' : '添加活动')"></el-page-header>
    
    <div class="form-container">
      <el-form 
        ref="activityForm" 
        :model="formData" 
        :rules="rules" 
        label-width="120px"
        :disabled="isView"
        v-loading="loading"
      >
        <el-form-item label="所属小区" prop="community.id">
          <el-select v-model="formData.community.id" placeholder="请选择小区" style="width: 100%" @change="handleCommunityChange">
            <el-option 
              v-for="item in communities" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入活动标题"></el-input>
        </el-form-item>
        
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="formData.location" placeholder="请输入活动地点"></el-input>
        </el-form-item>
        
        <el-form-item label="举办方" prop="organizer">
          <el-input v-model="formData.organizer" placeholder="请输入举办方"></el-input>
        </el-form-item>
        
        <el-form-item label="活动时间" prop="activityTime">
          <el-date-picker
            v-model="formData.activityTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        
        <el-form-item label="活动状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="未开始">未开始</el-radio>
            <el-radio label="进行中">进行中</el-radio>
            <el-radio label="已结束">已结束</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="活动内容" prop="content">
          <el-input 
            v-model="formData.content" 
            type="textarea" 
            :rows="5" 
            placeholder="请输入活动内容描述"
          ></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" v-if="!isView" :loading="submitting">保存</el-button>
          <el-button @click="goBack">{{ isView ? '返回' : '取消' }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import axios from 'axios';
import moment from 'moment';

export default {
  name: 'ActivityAdd',
  data() {
    return {
      isEdit: false,
      isView: false,
      loading: false,
      submitting: false,
      communities: [],
      formData: {
        community: {
          id: null,
          name: ''
        },
        title: '',
        location: '',
        organizer: '',
        activityTime: [],
        status: '未开始',
        content: ''
      },
      rules: {
        'community.id': [{ required: true, message: '请选择所属小区', trigger: 'change' }],
        title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
        location: [{ required: true, message: '请输入活动地点', trigger: 'blur' }],
        organizer: [{ required: true, message: '请输入举办方', trigger: 'blur' }],
        activityTime: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
        status: [{ required: true, message: '请选择活动状态', trigger: 'change' }],
        content: [{ required: true, message: '请输入活动内容', trigger: 'blur' }]
      },
      dateFormat: 'YYYY-MM-DD HH:mm:ss',
    };
  },
  created() {
    this.fetchCommunities();
    
    const id = this.$route.query.id;
    const view = this.$route.query.view;
    
    if (id) {
      this.isEdit = true;
      if (view === 'true') {
        this.isView = true;
      }
      this.fetchActivityData(id);
    }
  },
  mounted() {
    // 这部分功能已在created中处理
  },
  methods: {
    // 获取小区列表
    fetchCommunities() {
      axios.get('/api/communities')
        .then(response => {
          if (Array.isArray(response.data)) {
          this.communities = response.data;
          } else if (response.data && Array.isArray(response.data.content)) {
            this.communities = response.data.content;
          } else {
            this.communities = [];
          }
        })
        .catch(error => {
          console.error('获取小区列表失败:', error);
          ElMessage.error('获取小区列表失败');
        });
    },
    
    // 处理小区选择变更
    handleCommunityChange(communityId) {
      const selectedCommunity = this.communities.find(community => community.id === communityId);
      if (selectedCommunity) {
        this.formData.community.name = selectedCommunity.name;
      }
    },
    
    // 获取活动详情
    fetchActivityData(id) {
      this.loading = true;
      axios.get(`/api/activities/${id}`)
        .then(response => {
          const activity = response.data;
          console.log('获取到的活动数据:', activity);
          
          // 处理日期时间格式
          let startTime = activity.startTime ? this.formatDate(activity.startTime) : null;
          let endTime = activity.endTime ? this.formatDate(activity.endTime) : null;
          
          // 设置表单数据
          this.formData = {
            community: {
              id: activity.community ? activity.community.id : null,
              name: activity.community ? activity.community.name : ''
            },
            title: activity.title || '',
            location: activity.location || '',
            organizer: activity.organizer || '',
            activityTime: [startTime, endTime],
            status: activity.status || '未开始',
            content: activity.content || ''
          };
          
          // 记录社区ID，用于在小区列表中找到对应项
          if (activity.community && activity.community.id) {
            const communityId = activity.community.id;
            // 如果communities尚未加载完成，添加一个延迟处理
            if (this.communities.length === 0) {
              setTimeout(() => {
                const selectedCommunity = this.communities.find(c => c.id === communityId);
                if (selectedCommunity) {
                  this.formData.community.name = selectedCommunity.name;
                }
              }, 500);
            } else {
              const selectedCommunity = this.communities.find(c => c.id === communityId);
              if (selectedCommunity) {
                this.formData.community.name = selectedCommunity.name;
              }
            }
          }
          
          this.loading = false;
        })
        .catch(error => {
          console.error('获取活动详情失败:', error);
          ElMessage.error('获取活动详情失败: ' + (error.response?.data?.message || error.message));
          this.loading = false;
        });
    },
    
    submitForm() {
      this.$refs.activityForm.validate((valid) => {
        if (valid) {
          if (!this.formData.activityTime || this.formData.activityTime.length !== 2) {
            ElMessage.error('请选择完整的活动时间范围');
            return false;
          }
          
          this.submitting = true;
          this.submitActivity();
        } else {
          ElMessage.error('请填写完整信息');
          return false;
        }
      });
    },
    
    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return date.toISOString().slice(0, 19).replace('T', ' ');
    },
    
    // 解析日期
    parseDate(dateStr) {
      if (!dateStr) return null;
      return moment(dateStr, this.dateFormat).toDate();
    },
    
    // 提交活动数据
    submitActivity() {
      console.log('原始日期数据:', this.formData.activityTime);
      
      // 构建提交数据
      const submitData = {
        title: this.formData.title,
        content: this.formData.content,
        location: this.formData.location,
        organizer: this.formData.organizer,
        startTime: this.formData.activityTime[0] ? new Date(this.formData.activityTime[0]).getTime() : null,
        endTime: this.formData.activityTime[1] ? new Date(this.formData.activityTime[1]).getTime() : null,
        status: this.formData.status,
        community: {
          id: this.formData.community.id
        }
      };
      
      if (this.isEdit && this.$route.query.id) {
        submitData.id = parseInt(this.$route.query.id);
      }
      
      console.log('提交活动数据:', submitData);
      
      const url = this.isEdit 
        ? `/api/activities/${this.$route.query.id}`
        : '/api/activities';
      
      const request = this.isEdit
        ? axios.put(url, submitData)
        : axios.post(url, submitData);
        
      request
        .then(response => {
          console.log('活动保存响应:', response.data);
          ElMessage.success(this.isEdit ? '编辑成功' : '添加成功');
          this.submitting = false;
          setTimeout(() => {
            this.goBack();
          }, 500);
        })
        .catch(error => {
          console.error('活动保存失败:', error);
          
          if (error.response) {
            console.log('错误状态码:', error.response.status);
            console.log('错误头信息:', error.response.headers);
            console.log('错误数据:', error.response.data);
          }
          
          ElMessage.error('活动保存失败: ' + (error.response?.data?.message || error.message || '请检查表单数据'));
          this.submitting = false;
        });
    },
    
    goBack() {
      this.$router.push('/property/service/activity');
    }
  }
};
</script>

<style scoped>
.activity-add {
  padding: 20px;
}
.form-container {
  margin-top: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-size: 16px;
  font-weight: 500;
}
:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  font-size: 16px;
}
:deep(.el-button) {
  font-size: 16px;
  padding: 12px 20px;
}
:deep(.el-radio) {
  margin-right: 20px;
}
:deep(.el-page-header__title) {
  font-size: 18px;
  font-weight: 600;
}
</style>
